const PENDING = 'pengding'
const FUILLFILLED = 'fullfilled'
const REJECTED = 'rejected'


function myPromise(executor) {
    let self = this
    self.value = null // 接收resolve要抛出的值
    self.reason = null
    self.status = PENDING
    self.onFuilled = []  // 保存.then的第一个回调
    self.onRejected = [] // 保存then的第二个回调

    const resolve = (value) => {
        if(self.status !== PENDING) return
            self.value = value
            self.status = FUILLFILLED
            self.onFuilled.forEach(item =>{
                item(self.value)
            })
    
    }

    const reject = (reason) => {
        if(self.status !== PENDING) return
            self.reason = reason
            self.status = REJECTED
            self.onRejected.forEach(item =>{
                item(self.reason)
            })
    }

    executor && executor(resolve, reject)
}

myPromise.prototype.then = function(onFuill, onReject) {
    if(this.status == PENDING) {
        this.onFuilled.push(onFuill)
        this.onRejected.push(onReject)
    }
    else if(this.status == FUILLFILLED) { // 说明resolve已经执行
        onFuill(this.value)
    }
    else {
        onReject(this.reason)
    }
    return this
}


let a = new myPromise((resolve, reject) => {
    resolve('ok')
})
a.then(res => {
    console.log(res);
   
}) 


